<?php
class Users_controller extends CI_Controller{
	
	public function __construct(){
		parent::__construct();
        $this->load->model('user_model');
	}
   	
	public function index(){
		$this->load->view('users/users_list_view');
	}
	
   	/**
   	 * Gets a user from database
   	 * @param $id - task id
   	 * @see CRUD_interface::get()
   	 */
   	public function get($id = NULL){
   		$result = NULL;
   		if($id != NULL && $id != ''){
			$task = $this->task->get_task($id);
			$result = $task[0];
		}
		echo json_encode($result);
   	}
   	
   	/**
   	 * Saves a user into the database
   	 * @see CRUD_interface::save()
   	 */
   	public function save(){
   		$id			= $this->input->post('id');
   		$username 	= $this->input->post('username');
		$password	= $this->input->post('password');
		$name		= $this->input->post('name');
		$last_name	= $this->input->post('last_name');
		$email		= $this->input->post('email');
		$tel		= $this->input->post('tel');
		$dir		= $this->input->post('dir');
		$lan		= $this->input->post('language');
		$country	= $this->input->post('country');
		
		if($id != NULL && $id != ''){
			$this->user_model->update($id, $username, $password, $firstname, $lastname, $email, $tel, $address, $languaje, $country);
		}
		else{
			$insertId = $this->user_model->create($username, $password, $firstname, $lastname, $email, $tel, $address, $languaje, $country);
		}
			
		redirect('/index.php/users', 'refresh');
   	}
   	
   	/**
   	 * Removes an user from database
   	 * @param $id - task id
   	 * @see CRUD_interface::remove()
   	 */
   	public function remove($id = NULL){
   		$this->user_model->remove($id);
   		redirect('/index.php/authentication_controller/main_view/3' );
		//refresh list
   	}
   	
   	/**
   	 * Gets users list for jqgrid
   	 */
	function get_json_users_list(){
		$page	= $this->input->post('page');
		$limit 	= $this->input->post('rows');
		$sidx 	= $this->input->post('sidx');
		$sord 	= $this->input->post('sord');
		
		if(!$sidx) $sidx =1;
		
		$count = $this->user_model->get_users_count();

		if( $count > 0 ) {
			$total_pages = ceil($count/$limit);
		} else {
			$total_pages = 0;
		}
		if ($page > $total_pages) $page=$total_pages;
		$start = $limit*$page - $limit; // do not put $limit*($page - 1)
		
		$responce->page = $page;
		$responce->total = $total_pages;
		$responce->records = $count;
		
		$users = $this->user_model->get_users($sidx, $sord, $start , $limit); 
		
		for($i=0; $i< sizeof($users); $i++) {
			$responce->rows[$i]['id'] = $users[$i]['id'];
			$responce->rows[$i]['cell'] = array($users[$i]['id'], 
												$users[$i]['username'], 
												$users[$i]['firstname'],
												$users[$i]['lastname'], 
												$users[$i]['email']);
		}
     	
		echo json_encode($responce);
	}
}